package com.meichis.yndms.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.activity.TakePhotoActivity;
import com.google.android.entity.CameraParam;
import com.meichis.mcsappframework.dialog.DropDownPopupWindow;
import com.meichis.mcsappframework.utils.DateUtil;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.yndms.R;
import com.meichis.yndms.adapter.ImageAdapter;
import com.meichis.yndms.common.MCode;
import com.meichis.yndms.common.PictureUtils;
import com.meichis.yndms.databinding.ActivityVstFeedBackBinding;
import com.meichis.yndms.model.*;
import com.meichis.yndms.room.AppDatabase;
import com.meichis.yndms.ui.common.BaseActivity;
import com.meichis.yndms.vm.VstFeedBackVM;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class VST_FeedBackActivity extends BaseActivity {
    private static final int REQUEST_TAKEPHOTO = 0;


    private String workGuid, code;
    private String curDate = "1900-01-01";
    private List<Picture> piclist = new ArrayList<>();
    private List<DicDataItem> classifylist = new ArrayList<>();
    private List<DicDataItem> urgentFlaglist = new ArrayList<>();
    private int Classify = 0, urgentFlag = 0;

    private VisitWorkItem item;
    private ImageAdapter imageadapter;
    private ClientInfo RT;
    private UserInfo userInfo;
    private VstFeedBackVM vm;


    private ActivityVstFeedBackBinding binding;

    @Override
    protected void setDataBindingContentView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_vst_feed_back);
        vm = new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(VstFeedBackVM.class);
        binding.setVm(vm);
        binding.setClick(new ClickEvent());
        binding.setLifecycleOwner(this);
    }

    @Override
    protected void init() {
        ((TextView) findViewById(R.id.txtTitle)).setText("问题反馈");
        binding.navigation.navBack.setOnClickListener(v -> onBackPressed());

        curDate = DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS);
        workGuid = getIntent().getStringExtra(MCode.VISITGUID);
        RT = (ClientInfo) getIntent().getSerializableExtra(MCode.CLIENT);
        userInfo = (UserInfo) util.getObjectValue(SharePreferenceUtil.PREFERENCES_USERINFO);
        code = getIntent().getStringExtra(MCode.CODE);
        classifylist = AppDatabase.getInstance().dicDataItemDao().find("VST_IssueLog_IssueClassify");
        urgentFlaglist = AppDatabase.getInstance().dicDataItemDao().find("VST_IssueLog_UrgentFlag");
        item = AppDatabase.getInstance().visitWorkItemDao().find(workGuid, code);
        if (item != null) {
            piclist.clear();
            piclist.addAll(PictureUtils.Attachment2Picture(item.getAtts()));
        }
        imageadapter = new ImageAdapter(this, R.layout.activity_signin_photoitem, piclist);
        imageadapter.setonDeleteListener(position -> {
            binding.ibtTakephoto.setVisibility(piclist.size() < 6 ? View.VISIBLE : View.GONE);
            return null;
        });

        binding.RVPhotoList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        if (item == null) {
            if (classifylist.size() > 0) {
                binding.btClassify.setText(classifylist.get(0).getName());
                Classify = classifylist.get(0).getID();
            }
            if (urgentFlaglist.size() > 0) {
                binding.btUrgentFlag.setText(urgentFlaglist.get(0).getName());
                urgentFlag = urgentFlaglist.get(0).getID();
            }
        } else {
            binding.btClassify.setText(item.getIssueLog().getIssueClassifyName());
            Classify = item.getIssueLog().getIssueClassify();
            binding.btUrgentFlag.setText(item.getIssueLog().getUrgentFlagName());
            urgentFlag = item.getIssueLog().getUrgentFlag();
            binding.etContent.setText(item.getIssueLog().getContent());
        }
        binding.RVPhotoList.setAdapter(imageadapter);
    }


    public class ClickEvent {

        public void onSelectClassify(View v) {
            new DropDownPopupWindow<>(VST_FeedBackActivity.this, "Name", classifylist, position -> {
                binding.btClassify.setText(classifylist.get(position).getName());
                Classify = classifylist.get(position).getID();
            }).showAsDropDown(v);
        }

        public void onUrgentFlag(View v) {
            new DropDownPopupWindow<>(VST_FeedBackActivity.this, "Name", urgentFlaglist, position -> {
                binding.btUrgentFlag.setText(urgentFlaglist.get(position).getName());
                urgentFlag = urgentFlaglist.get(position).getID();
            }).showAsDropDown(v);
        }

        public void onContainer() {
            binding.etContent.requestFocus();
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(binding.etContent, InputMethodManager.SHOW_FORCED);
        }

        public void onTakephoto() {
            Intent intent = new Intent(VST_FeedBackActivity.this, TakePhotoActivity.class);
            CameraParam takePhotoParam = new CameraParam(CameraParam.Quantity.Low);
            takePhotoParam.setWatermark("拍摄时间：" + DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS) +
                    "\n拍摄地址：" + util.getStringValue(SharePreferenceUtil.PREFERENCES_VSTLOCATION + RT.getID())
                    + "\n员工编码：" + userInfo.getUsername()
                    + "\n员工姓名：" + userInfo.getName());
            intent.putExtra("CameraParam", takePhotoParam);
            startActivityForResult(intent, REQUEST_TAKEPHOTO);
        }

        public void onSave(){
            VisitWorkItem_IssueLog issueLog = new VisitWorkItem_IssueLog();
            issueLog.setClient(RT.getID());
            issueLog.setIssueClassify(Classify);
            issueLog.setIssueClassifyName(binding.btClassify.getText().toString());
            issueLog.setUrgentFlag(urgentFlag);
            issueLog.setUrgentFlagName(binding.btUrgentFlag.getText().toString());
            issueLog.setContent(binding.etContent.getText().toString().trim());

            if (item == null) {
                item = new VisitWorkItem();
                item.setVisitGUID(workGuid);
                item.setProcessCode(code);
                item.setWorkTime(curDate);
                item.setEndTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
                item.setIssueLog(issueLog);
                item.setAtts(PictureUtils.Picture2Attachment(piclist));
                AppDatabase.getInstance().visitWorkItemDao().insert(item);
            } else {
                item.setEndTime(DateUtil.getCurDateStr(DateUtil.FORMAT_YMDHMS));
                item.setIssueLog(issueLog);
                item.setAtts(PictureUtils.Picture2Attachment(piclist));
                AppDatabase.getInstance().visitWorkItemDao().update(item);
            }
            showMsg("保存成功");
            setResult(RESULT_OK);
            close();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_CANCELED) return;
        switch (requestCode) {
            case REQUEST_TAKEPHOTO:
                String picPath = data.getExtras().getString("result");
                if (!TextUtils.isEmpty(picPath)) {
                    Picture pic = new Picture();
                    pic.setVisitGuid(workGuid);
                    pic.setProcessCode(code);
                    pic.setFilePath(picPath);
                    pic.setGuid(UUID.randomUUID().toString());
                    pic.setRelateType(4);//拜访
                    pic.setFillName(picPath.substring(picPath.lastIndexOf("/") + 1));
                    AppDatabase.getInstance().pictureDao().insert(pic);
                    piclist.add(pic);
                }
                if (piclist.size() >= 6)
                    binding.ibtTakephoto.setVisibility(View.GONE);
                imageadapter.notifyDataSetChanged();
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
